from rest_framework.generics import ListAPIView, RetrieveAPIView, ListCreateAPIView, get_object_or_404
from rest_framework.permissions import IsAuthenticated
from .serializers import ForumPostSerializer
from rest_framework.pagination import PageNumberPagination
from .models import PostComment
from .serializers import PostCommentSerializer
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from .serializers import ForumPostCreateSerializer
from rest_framework.parsers import MultiPartParser
from .models import ForumPost, PostImage, PostLike
from .models import PostFavorite
from rest_framework.generics import ListAPIView
from .serializers import ForumPostSerializer
from rest_framework.permissions import IsAuthenticated



class ForumPostPagination(PageNumberPagination):
    page_size = 10


class ForumPostListView(ListAPIView):
    queryset = ForumPost.objects.select_related('user').prefetch_related('images', 'postlike_set', 'comments').order_by(
        '-created_at')
    serializer_class = ForumPostSerializer
    pagination_class = ForumPostPagination


class ForumPostDetailView(RetrieveAPIView):
    queryset = ForumPost.objects.all()
    serializer_class = ForumPostSerializer

    def get_serializer_context(self):
        context = super().get_serializer_context()
        context['request'] = self.request  # 必须有
        return context


class PostCommentListCreateView(ListCreateAPIView):
    permission_classes = [IsAuthenticated]
    serializer_class = PostCommentSerializer

    def get_queryset(self):
        post_id = self.kwargs['post_id']
        return PostComment.objects.filter(post_id=post_id).select_related('user').order_by('-created_at')

    def perform_create(self, serializer):
        serializer.save(user=self.request.user, post_id=self.kwargs['post_id'])


class ForumPostCreateView(APIView):
    permission_classes = [IsAuthenticated]

    def post(self, request):
        serializer = ForumPostCreateSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save(user=request.user)
            post = serializer.save(user=request.user)
            return Response({'message': '发布成功',
                             'id': post.id,
                             }, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


# forum/views.py


class ForumPostImageUploadView(APIView):
    permission_classes = [IsAuthenticated]
    parser_classes = [MultiPartParser]

    def post(self, request, post_id):
        post = ForumPost.objects.get(id=post_id, user=request.user)
        image = request.FILES.get('image')
        if image:
            PostImage.objects.create(post=post, url=image)
            return Response({'message': '图片上传成功'}, status=status.HTTP_201_CREATED)
        return Response({'error': '没有图片'}, status=status.HTTP_400_BAD_REQUEST)



# 点赞视图

class PostLikeView(APIView):
    permission_classes = [IsAuthenticated]

    def post(self, request, post_id):
        post = ForumPost.objects.get(id=post_id)
        like, created = PostLike.objects.get_or_create(user=request.user, post=post)
        if created:
            return Response({'message': '点赞成功'}, status=status.HTTP_201_CREATED)
        return Response({'message': '您已经点赞过'}, status=status.HTTP_400_BAD_REQUEST)

    def delete(self, request, post_id):
        post = ForumPost.objects.get(id=post_id)
        PostLike.objects.filter(user=request.user, post=post).delete()
        return Response({'message': '取消点赞成功'}, status=status.HTTP_204_NO_CONTENT)



#收藏视图

class PostFavoriteToggleView(APIView):
    permission_classes = [IsAuthenticated]

    def post(self, request, post_id):
        post = get_object_or_404(ForumPost, id=post_id)
        favorite, created = PostFavorite.objects.get_or_create(user=request.user, post=post)
        if created:
            return Response({'message': '已收藏'}, status=201)
        else:
            favorite.delete()
            return Response({'message': '已取消收藏'}, status=200)



# forum/views.py

class MyFavoritePostsView(ListAPIView):
    permission_classes = [IsAuthenticated]
    serializer_class = ForumPostSerializer
    pagination_class = ForumPostPagination

    def get_queryset(self):
        return ForumPost.objects.filter(postfavorite__user=self.request.user).select_related('user').prefetch_related('images')
